<template>
  <div class="menu-management-container">
    <el-row :gutter="20">
      <el-col :lg="6" :md="6" :sm="24" :xl="4" :xs="24">
        <vab-card shadow="hover">
          <el-tree
            ref="treeRef"
            :data="data"
            :default-expanded-keys="expandDefault"
            highlight-current
            node-key="id"
            :props="defaultProps"
            @node-click="handleNodeClick"
          >
            <template #default="{ node }">
              <span class="custom-tree-node">
                <!-- <span @click="handleNodeClick(data)">{{ node.label }}</span> -->
                <span>{{ node.label }}</span>
                <!-- <span>
                  <a
                    v-if="MenuAuth('add')"
                    style="margin-left: 10px"
                    @click="treeEdit(data, 'add')"
                  >
                    新增
                  </a>
                  <a
                    v-if="MenuAuth('edit')"
                    style="margin-left: 10px"
                    @click="treeEdit(data, 'edit')"
                  >
                    编辑
                  </a>
                  <a
                    v-if="MenuAuth('delete')"
                    style="margin-left: 8px"
                    @click="remove(data)"
                  >
                    删除
                  </a>
                </span> -->
              </span>
            </template>
          </el-tree>
        </vab-card>
      </el-col>
      <el-col :lg="18" :md="18" :sm="24" :xl="20" :xs="24">
        <vab-card shadow="hover">
          <vab-query-form>
            <vab-query-form-top-panel :span="12">
              <el-button
                v-if="MenuAuth('add')"
                :icon="Plus"
                type="primary"
                @click="handleEdit()"
                plain
              >
                {{ translate('添加') }}
              </el-button>
              <el-dropdown trigger="click">
                <el-button type="primary" plain>
                  {{ translate('分类管理') }}
                  <el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      v-if="MenuAuth('add')"
                      @click="treeEdit('add')"
                    >
                      {{ translate('新增') }}
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="MenuAuth('edit')"
                      @click="treeEdit('edit')"
                    >
                      {{ translate('编辑') }}
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="MenuAuth('delete')"
                      @click="remove()"
                    >
                      {{ translate('删除') }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </vab-query-form-top-panel>
          </vab-query-form>
          <el-table
            v-loading="listLoading"
            border
            :data="list"
            default-expand-all
            row-key="path"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          >
            <el-table-column
              :label="translate('项目名称')"
              prop="FullName"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('项目值')"
              prop="Code"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('是否有效')"
              show-overflow-tooltip
            >
              <template #default="{ row }">
                {{ row.Enabled ? translate('是') : translate('否') }}
              </template>
            </el-table-column>
            <el-table-column
              :label="translate('创建人')"
              prop="CreateUserName"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('创建时间')"
              prop="CreateDate"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('修改人')"
              prop="ModifyUserName"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('修改时间')"
              prop="ModifyDate"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('操作')"
              show-overflow-tooltip
              width="200"
            >
              <template #default="{ row }">
                <el-button
                  v-if="MenuAuth('edit')"
                  size="small"
                  type="primary"
                  @click="handleEdit(row, 'edit')"
                  plain
                >
                  {{ translate('编辑') }}
                </el-button>
                <el-button
                  v-if="MenuAuth('delete')"
                  size="small"
                  type="danger"
                  @click="handleDelete(row)"
                  plain
                >
                  {{ translate('删除') }}
                </el-button>
              </template>
            </el-table-column>
            <template #empty>
              <!-- <el-image
                class="vab-data-empty"
                :src="require('@/assets/empty_images/data_empty.png')"
              /> -->
              <el-empty
                class="vab-data-empty"
                :description="translate('暂无数据')"
              />
            </template>
          </el-table>
        </vab-card>
      </el-col>
    </el-row>
    <edit ref="editRef" :tree="tree" @fetch-data="fetchData" />
    <treeEdit ref="treeEditRef" :tree="data" @tree-save="getTree" />
  </div>
</template>

<script>
  import {
    doDelete,
    getTreeJson,
    getList,
    deleteDictionaryDetail,
  } from '@/api/dictionary'
  import { Plus } from '@element-plus/icons-vue'
  import { MenuAuth } from '~/src/utils/permission'
  import { translate } from '@/i18n'
  export default defineComponent({
    name: 'Dictionary',
    components: {
      Edit: defineAsyncComponent(() => import('./components/DictionaryEdit')),
      TreeEdit: defineAsyncComponent(() =>
        import('./components/DictionaryTreeEdit')
      ),
    },
    setup() {
      const $baseConfirm = inject('$baseConfirm')
      const $baseMessage = inject('$baseMessage')

      const state = reactive({
        editRef: null,
        treeRef: null,
        treeEditRef: null,
        data: [],
        treeParams: {},
        tree: [],
        defaultProps: {
          children: 'ChildNodes',
          label: 'text',
        },
        list: [],
        queryForm: {
          dataDictionaryId: 'string',
          dataDictionaryDetailId: 'string',
          parentId: 'string',
          code: 'string',
        },
        listLoading: true,
        expandDefault: [],
        checkID: '',
      })
      //列表编辑
      const handleEdit = (row, type) => {
        state.treeParams.ChildNodes = []
        let childrens = JSON.stringify(state.list).replace(/FullName/g, 'text')
        childrens = JSON.parse(childrens)
        state.treeParams.ChildNodes.push(...childrens)
        state.treeParams.ID = state.treeParams.id
        state.tree = [state.treeParams]
        if (row && row.DataDictionaryDetailId) {
          state['editRef'].showEdit(row, type)
        } else {
          const val = row ? row : state.queryForm
          val.id = val.dataDictionaryId
          if (!row) state['editRef'].showEdit(val, type)
        }
      }
      //树形删除
      const remove = () => {
        if (state.queryForm.dataDictionaryId) {
          $baseConfirm(translate('你确定要删除当前项吗'), null, async () => {
            const { message } = await doDelete({
              dataDictionaryId: state.queryForm.dataDictionaryId,
              dataDictionaryDetailId: 'string',
              parentId: 'string',
              code: 'string',
            })
            //删除列表默认回到第一页
            state.queryForm.pageNo = 1
            $baseMessage(message, 'success', 'vab-hey-message-success')
            // await fetchData(state.queryForm)
            getTree(true)
          })
        }
      }
      //列表删除
      const handleDelete = (row) => {
        if (row.DataDictionaryDetailId) {
          $baseConfirm(translate('你确定要删除当前项吗'), null, async () => {
            const { message } = await deleteDictionaryDetail({
              DataDictionaryDetailId: row.DataDictionaryDetailId,
            })
            //删除列表默认回到第一页
            state.queryForm.pageNo = 1
            $baseMessage(message, 'success', 'vab-hey-message-success')
            await fetchData(state.queryForm)
          })
        }
      }
      //菜单表格
      const fetchData = async (role) => {
        state.listLoading = true
        const {
          data: { data },
        } = await getList({
          dataDictionaryId: state.queryForm.dataDictionaryId,
          dataDictionaryDetailId: 'string',
          parentId: 'string',
          code: 'string',
        })
        if (data) state.list = JSON.parse(data).rows
        state.listLoading = false
      }
      //树形数据点击
      const handleNodeClick = (row) => {
        state.queryForm.dataDictionaryId = row.id
        state.queryForm.id = row.id
        state.queryForm.parentnodes = row.parentnodes
        state.treeParams = JSON.parse(JSON.stringify(row))
        fetchData()
      }
      //获取树形结构下第一个ID
      const getFirstNode = (tree) => {
        if (tree?.ChildNodes && tree?.ChildNodes.length > 0) {
          getFirstNode(tree.ChildNodes[0])
        } else {
          if (tree) {
            state.queryForm.code = tree?.id
            state.queryForm.companyId = tree?.CompanyId
            state.queryForm.dataDictionaryId = tree?.id
            state.treeParams = JSON.parse(JSON.stringify(tree))
            nextTick(() => {
              state['treeRef'].setCurrentKey(tree?.id)
            })
          } else {
            state.listLoading = false
          }

          return
        }
      }
      //树形结构数据
      const getTree = async (getListData) => {
        const {
          data: { data },
        } = await getTreeJson()
        state.data = JSON.parse(data)
        if (getListData) {
          // 是否需要获取第一项节点列表数据
          getFirstNode(state.data[0])
          state.expandDefault.push(state.queryForm.dataDictionaryId)
          fetchData(state.queryForm)
        } else {
          const currentNode = (nodes) => {
            nodes.map((item) => {
              if (item.id === state.queryForm.dataDictionaryId) {
                state.treeParams = JSON.parse(JSON.stringify(item))
              } else {
                if (item.ChildNodes) {
                  currentNode(item.ChildNodes)
                }
              }
            })
          }
          currentNode(state.data)
          nextTick(() => {
            state['treeRef'].setCurrentKey(state.queryForm.dataDictionaryId)
          })
        }
      }
      getTree(true)
      // getTreeJson().then(({ data }) => {
      //   if (data) {
      //     const list = data.data
      //     state.data = JSON.parse(list)
      //     //默认选中第一个
      //     getFirstNode(state.data[0])
      //     state.expandDefault.push(state.queryForm.dataDictionaryId)
      //     fetchData(state.queryForm)
      //   }
      // })
      const treeEdit = (type) => {
        if (state.queryForm.dataDictionaryId) {
          state['treeEditRef'].showEdit(
            {
              id: state.queryForm.dataDictionaryId,
              companyId: state.queryForm.companyId,
            },
            type
          )
        } else {
          const val = row ? row : state.queryForm
          if (!row) state['treeEditRef'].showEdit(val, type)
        }
      }
      // const treeEdit = (row, type) => {
      //   if (row && row.id) {
      //     state['treeEditRef'].showEdit(row, type)
      //   } else {
      //     const val = row ? row : state.queryForm
      //     if (!row) state['treeEditRef'].showEdit(val, type)
      //   }
      // }
      return {
        ...toRefs(state),
        handleEdit,
        handleDelete,
        fetchData,
        handleNodeClick,
        Plus,
        treeEdit,
        remove,
        MenuAuth,
        getTree,
        translate,
      }
    },
  })
</script>

<style lang="scss" scoped>
  $base: '.menu-management';
  #{$base}-container {
    padding: 0 !important;
    background: $base-color-background !important;
  }
  ::v-deep .el-dropdown {
    margin: 0 10px 10px 0;
  }
</style>
